package blueq.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import blueq.entity.mongo.AppInfo;
import blueq.entity.mongo.AppResult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonParser {
	
	
	public static String parseResult(AppInfo appinfo) {
		AppResult app = new AppResult();
		app.setIconURL(appinfo.getApp_icon_url());
		app.setComment(appinfo.getApp_desc());
		app.setInstallCount(appinfo.getApp_data_install());
		app.setName(appinfo.getApp_name());
		app.setSize(appinfo.getApp_size());
		return JSON.toJSONString(app);
	}

	/**
	 * 将数据库内容转换为请求需要的格式
	 * @param list
	 * @return
	 */
	public static String parseResult(List<AppInfo> list) {
		List<AppResult> applist = new ArrayList<AppResult>();
		for(AppInfo appinfo : list) {
			AppResult app = new AppResult();
			app.setIconURL(appinfo.getApp_icon_url());
			app.setComment(appinfo.getApp_desc());
			app.setInstallCount(appinfo.getApp_data_install()+"万");
			app.setName(appinfo.getApp_name());
			app.setSize(appinfo.getApp_size());
			app.setId(parseUrl(appinfo.getApp_download_url()));
			applist.add(app);
		}
		Map<String, List<AppResult>> map = new HashMap<String, List<AppResult>>();
		map.put("icons", applist);
			
		return JSON.toJSONString(map);
	}
	
	/**
	 * 从下载地址中提取出app_id
	 * @param url
	 * @return
	 */
	private static String parseUrl(String url) {
		//"http://apps.wandoujia.com/apps/com.sankuai.movie/download"
		url = url.substring(url.indexOf("apps/")+5,url.indexOf("/download"));
		return url;
	}
}
